; (function (undefined) {
    var _global;
    var _baseUrl = '';

    function result(args, fn) {
        var argsArr = Array.prototype.slice.call(args);
        if (argsArr.length > 0) {
            return argsArr.reduce(fn);
        } else {
            return 0;
        }
    }

    // 格式化参数
    function formatParams(data) {
        var arr = [];
        for (var name in data) {
            arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
        }
        arr.push(('v=' + Math.random()).replace('.', ''));
        return arr.join('&');
    }

    // 获取URL参数
    function getUrlParameter(url, name) {
        const reg = RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
        let params = url.split('?')[1]
        let param = params.match(reg)
        if (param !== null) {
            return unescape(param[2])
        }
        return null
    }

    // 从Cookie中取值
    function getCookie(name) {
        var strcookie = document.cookie;//获取cookie字符串
        var arrcookie = strcookie.split("; ");//分割
        //遍历匹配
        for (var i = 0; i < arrcookie.length; i++) {
            var arr = arrcookie[i].split("=");
            if (arr[0] == name) {
                return arr[1];
            }
        }
        return ""
    }

    /**
     * 往sessionStorage里写值
     * @param {*} key 
     * @param {*} value 
     */
    function saveSessionStorage(key, value) {
        sessionStorage.setItem(key, value)
    }

    /**
     * 从sessionStorage里取值
     * @param {*} key 
     */
    function getSessionStorage(key) {
        return sessionStorage.getItem(key)
    }
    
    /**
     * 往localStorage里写值
     */
    function saveLocalStorage(key, value) {
    	localStorage.setItem(key, value)
    }
    
    /**
     * 从localStorage取值
     */
    function getLocalStorage(key) {
    	return localStorage.getItem(key)
    }

    // 创建ajax函数
    function ajax(options) {
        options = options || {};
        options.type = (options.type || 'GET').toUpperCase();
        options.dataType = options.dataType || 'json';
        params = formatParams(options.data);

        // 创建-第一步
        var xhr;
        // 非IE6
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else {
            // ie6及其以下版本浏览器
            xhr = ActiveXObject('Microsoft.XMLHTTP');
        }

        // 接收-第三步
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                var status = xhr.status;
                if (status >= 200 && status < 300) {
                    options.success && options.success(xhr.responseText, xhr.responseXML);
                } else {
                    options.error && options.error(status);
                }
            }
        }

        // 连接和发送-第二步
        if (options.type == 'GET') {
            xhr.open('GET', options.url + '?' + params, true);
            xhr.send(null);
        } else if (options.type == 'POST') {
            xhr.open('POST', options.url, true);
            // 设置表单提交时的内容类型
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.send(params);
        }
    }

    // 清除Cookie
    function delCookie() {
        var keys = document.cookie.match(/[^ =;]+(?==)/g)
        if (keys) {
            for (var i = keys.length; i--;) {
                document.cookie = keys[i] + '=0;path=/;expires=' + new Date(0).toUTCString() // 清除当前域名下的,例如：m.ratingdog.cn
                document.cookie = keys[i] + '=0;path=/;domain=' + document.domain + ';expires=' + new Date(0).toUTCString() // 清除当前域名下的，例如 .m.ratingdog.cn
                document.cookie = keys[i] + '=0;path=/;domain=ratingdog.cn;expires=' + new Date(0).toUTCString() // 清除一级域名下的或指定的，例如 .ratingdog.cn
            }
        }
    }

    var power = {
        // 配置后端地址
        config: function (options) {
            if (options.url) {
                _baseUrl = options.url
            }
        },
        saveSessionUser: function (user = {}) {
            let token = getCookie(this.AUTHORIZATION)
            let base_user = getCookie(this.USER)
            if (token) {
                saveSessionStorage(this.ACCESS_TOKEN, token)
            }
            if (base_user) {
                let baseUser = JSON.parse(decodeURIComponent(base_user))
                saveSessionStorage(this.BASEUSER, decodeURIComponent(base_user))
                saveSessionStorage(this.USERID, baseUser.userid)
                saveSessionStorage(this.EXTERNAL_USERID, baseUser.external_userid)
                saveSessionStorage(this.APPID, baseUser.appid)
            }
			if (user) {
                saveSessionStorage(this.USER, JSON.stringify(user))
            }
            delCookie()
            return this.getSessionUser()
        },
        getSessionUser: function () {
			let user = JSON.parse(getSessionStorage(this.BASEUSER));
			if(user) {
				user[this.USER]= JSON.parse(getSessionStorage(this.USER))
				return user;
			}else {
				return {};
			}
        },
        getSessionUserId: function() {
            return getSessionStorage(this.USERID)
        },
        getSessionExternalUserId: function() {
            return getSessionStorage(this.EXTERNAL_USERID)
        },
        getSessionAppId: function() {
            return getSessionStorage(this.APPID)
        },
		// 保存第三方客户信息
		saveCustomerInfo: function (info = {}) {
			if(info) {
				saveSessionStorage(this.CUSTOMER_INFO, JSON.stringify(info))
			}
		},
		// 获取第三方客户信息
		getCustomerInfo: function () {
			return JSON.parse(getSessionStorage(this.CUSTOMER_INFO));
		},
		// 保存第三方客户关键信息
		saveKeyCustomerInfo: function (keyInfo = []) {
			if(keyInfo) {
				saveSessionStorage(this.KEY_INFO, JSON.stringify(keyInfo))
			}
		},
		// 获取第三方客户关键信息
		getKeyCustomerInfo: function () {
			return JSON.parse(getSessionStorage(this.KEY_INFO));
		},
		// 保存业务岗位信息
		saveBizPostInfo: function (info = {}) {
			if(info) {
				saveSessionStorage(this.BIZPOSTS, JSON.stringify(info))
			}
		},
		// 获取业务岗位信息
		getBizPostInfo: function () {
			return JSON.parse(getSessionStorage(this.BIZPOSTS));
		},
		// 保存客户经理信息
		saveManagerInfo: function (info = {}) {
			if(info) {
				saveSessionStorage(this.MANAGER_INFO, JSON.stringify(info))
			}
		},
		// 获取客户经理信息
		getManagerInfo: function () {
			return JSON.parse(getSessionStorage(this.MANAGER_INFO));
		},
        saveLocalUser: function (user = {}) {
            let token = getCookie(this.AUTHORIZATION)
            let base_user = getCookie(this.USER)
            if (token) {
            	saveLocalStorage(this.ACCESS_TOKEN, token)
            }
			if (base_user) {
                let baseUser = JSON.parse(decodeURIComponent(base_user))
                saveLocalStorage(this.BASEUSER, decodeURIComponent(base_user))
                saveLocalStorage(this.USERID, baseUser.userid)
                saveLocalStorage(this.EXTERNAL_USERID, baseUser.external_userid)
                saveLocalStorage(this.APPID, baseUser.appid)
            }
			if (user) {
                saveLocalStorage(this.USER, JSON.stringify(user))
            }
            delCookie()
            return this.getLocalUser()
        },
        getLocalUser: function () {
			let user = JSON.parse(getLocalStorage(this.BASEUSER))
			user[this.USER]= JSON.parse(getLocalStorage(this.USER))
            return user;
        },
        getLocalUserId: function() {
            return getLocalStorage(this.USERID)
        },
        getLocalExternalUserId: function() {
            return getLocalStorage(this.EXTERNAL_USERID)
        },
        getLocalAppId: function() {
            return getLocalStorage(this.APPID)
        },
        AUTHORIZATION: 'Authorization',
        USERID: 'userid',
        OPENID: 'openid',
        EXTERNAL_USERID: 'external_userid',
        ACCESS_TOKEN: 'token',
        CORPID: 'corpid',
        APPID: 'appid',
        USER: 'user',
        USERNAME: 'username',
        MOBILE: 'mobile',
		BASEUSER: 'base_user',
		CUSTOMER_INFO: 'customer_info',	// 第三方客户信息
		KEY_INFO: 'keyCustomer_info',
		BIZPOSTS: 'bizposts', // 第三方岗位信息
		MANAGER_INFO: 'manager_info', // 客户经理信息
    }

    // 将插件对象暴露给全局对象
    _global = (function () { return this || (0, eval)('this'); }());
    if (typeof module !== "undefined" && module.exports) {
        module.exports = power;
    } else if (typeof define === "function" && define.amd) {
        define(function () { return power; });
    } else {
        !('power' in _global) && (_global.power = power);
    }
}());